package top.leetcode;

/**
 * @Desc
 * @Author houruiyang
 * @Date 2022/12/20
 **/
public class _002 {
    public static void main(String[] args) {
        ListNode n1 = new ListNode(2);
        ListNode n2 = new ListNode(4);
        ListNode n3 = new ListNode(3);
        n1.next = n2;
        n2.next = n3;


        ListNode n4 = new ListNode(5);
        ListNode n5 = new ListNode(6);
        ListNode n6 = new ListNode(4);
        n4.next = n5;
        n5.next = n6;

        ListNode listNode = addTwoNumbers(n1, n4);

        System.out.println(listNode.toString());
    }

    public static ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode pre = new ListNode(0);
        ListNode cur = pre;
        // 用于存储十位上的数字
        int carry = 0;
        while (l1 != null || l2 != null) {
            int x = l1 == null ? 0 : l1.val;
            int y = l2 == null ? 0 : l2.val;
            int sum = x + y + carry;
            carry = sum / 10;
            sum = sum % 10;
            cur.next = new ListNode(sum);
            cur = cur.next;
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry == 1) {
            cur.next = new ListNode(carry);
        }

        return pre.next;

//        ListNode pre = new ListNode(0);
//        ListNode cur = pre;
//        int carry = 0;
//        while(l1 != null || l2 != null) {
//            int x = l1 == null ? 0 : l1.val;
//            int y = l2 == null ? 0 : l2.val;
//            int sum = x + y + carry;
//
//            carry = sum / 10;
//            sum = sum % 10;
//            cur.next = new ListNode(sum);
//
//            cur = cur.next;
//            if(l1 != null){
//                l1 = l1.next;
//            }
//            if(l2 != null){
//                l2 = l2.next;
//
//            }
//        }
//        if(carry == 1) {
//            cur.next = new ListNode(carry);
//        }
//        return pre.next;


    }

    static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

}
